package ru.dveriwell.intra.util;

import java.util.Collection;
import java.util.LinkedList;

import com.vaadin.data.Container;
import com.vaadin.data.util.BeanContainer;


public class UserHierarchicalBeanContainer<IDTYPE,BEANTYPE> extends BeanContainer<IDTYPE,BEANTYPE> implements Container.Hierarchical {

	private static final long serialVersionUID = -3288623832258854024L;
	
	Object parentPID;

	public UserHierarchicalBeanContainer(Class<? super BEANTYPE> type,
            Object parentPropertyId) {
        super(type);
        
        this.parentPID = parentPropertyId;
    }

    @Override
    public Collection<?> getChildren(Object itemId) {
        LinkedList<Object> children = new LinkedList<Object>();

        for (Object candidateId: getItemIds()) {
            Object parentRef = getItem(candidateId).
                    getItemProperty(parentPID).getValue();
            if (itemId.equals(parentRef))
                children.add(candidateId);
        }
        
        if (children.size() > 0) {
            return children;
        } else
            return null;
    }

    @Override
    public Object getParent(Object itemId) {
        return getItem(itemId).
                getItemProperty(parentPID).getValue();
    }

    @Override
    public Collection<?> rootItemIds() {
    	
        LinkedList<Object> result = new LinkedList<Object>();
        for (Object candidateId: getItemIds()) {
            Object parentRef = getItem(candidateId).
                    getItemProperty(parentPID).getValue();
            if (parentRef == null)
                result.add(candidateId);
        }
        
        if (result.size() > 0)
            return result;
        else
            return null;
    }

    @Override
    public boolean setParent(Object itemId, Object newParentId)
        throws UnsupportedOperationException {
        throw new UnsupportedOperationException(
            "Not implemented here");
    }

    @Override
    public boolean areChildrenAllowed(Object itemId) {
        return hasChildren(itemId);
    }

    @Override
    public boolean setChildrenAllowed(Object itemId,
                                      boolean childrenAllowed)
            throws UnsupportedOperationException {
        throw new UnsupportedOperationException(
                "Not implemented here");
    }

    @Override
    public boolean isRoot(Object itemId) {
        return getItem(itemId).getItemProperty(parentPID).
                getValue() == null;
    }

    @Override
    public boolean hasChildren(Object itemId) {
    	
        for (Object candidateId: getItemIds()) {

        	Object parentRef = getItem(candidateId).
                    getItemProperty(parentPID).getValue();
        	
            if (itemId.equals(parentRef))
            	return true;
        }
        return false;
    }
	
}
